package com.fantabest.common.server.dao;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.apache.log4j.Logger;

import com.fantabest.common.PMF;
import com.fantabest.common.entity.Player;
import com.fantabest.common.entity.Season;

public class PlayerDao {

	private static final Logger log = Logger.getLogger(PlayerDao.class);
	
	private static PlayerDao instance;

	public static PlayerDao getInstance() {
		if(instance == null)
			instance = new PlayerDao();
		return instance;
	}
	
	
	public void save(Player player)	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(player);
		} catch (Exception e) {
			e.printStackTrace();
		}	finally	{
			pm.close();
		}
	}
	
	
	public void save(List<Player> playersList, Long seasonId)	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Season season = pm.getObjectById(Season.class, seasonId);
			season.setPlayersList(playersList);
			pm.makePersistent(season);
		} catch (Exception e) {
			e.printStackTrace();
		}	finally	{
			pm.close();
		}
		
	}
	
	public void deleteAll()	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Player.class);
		long result = 0;
		try {
			result = q.deletePersistentAll();
			log.debug(result +" players deleted");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			q.closeAll();
		}
	}
	
	public List<Player> findByPosition(String position)	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Player.class);
		q.setOrdering("quotation desc");
		q.setFilter("position == pposition");
		q.declareParameters("String pposition");
		List<Player> results = null;
		try {
			List<Player> sqr = (List<Player>) q.execute(position);
			results =  (List<Player>)pm.detachCopyAll(sqr);
			log.debug(results.size() + " players loaded from datastore");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			q.closeAll();
		}
		return results;
	}
	
	public List<Player> findAll()	{
		return null;
	}
	
}
